package com.solo.quartz.service.inner;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.extra.spring.SpringUtil;
import com.solo.quartz.api.entity.QrtzJob;
import com.solo.quartz.api.entity.QrtzJobLog;
import com.solo.quartz.service.QrtzJobLogService;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 定时任务记录
 * <p>
 * Quartz被集成在Spring框架之后，任务类自然会以Bean对象的方式被管理
 * 在任务创建时，设置要执行的作业类QuartzRecord，该类继承QuartzJobBean抽象类
 * 通过重写executeInternal方法，来管理任务实际执行的逻辑
 * </p>
 * @author 十一
 * @since 2024/08/19
 * 人生若只如初见，何事秋风悲画扇
 **/
public class QuartzRecord extends QuartzJobBean {

    @Override
    protected void executeInternal(JobExecutionContext context) {
        QrtzJob job = (QrtzJob) context.getMergedJobDataMap().get("scheduleJob");
        QrtzJobLogService qrtzJobLogService = SpringUtil.getBean(QrtzJobLogService.class);
        // 定时器日志记录
        QrtzJobLog log = new QrtzJobLog();
        log.setJobId(job.getJobId());
        log.setCreateTime(LocalDateTime.now());
        TimeInterval timer = DateUtil.timer();
        try {
            // 加载并执行
            Object target = SpringUtil.getBean(job.getHandlerName());
            Method method = target.getClass().getDeclaredMethod("run", String.class);
            method.invoke(target, job.getHandlerParams());
            log.setStatus(true);
        } catch (Exception e) {
            log.setStatus(false);
            log.setExceptionInfo(e.getMessage());
        } finally {
            // 保存执行日志
            long executeTime = timer.interval();
            log.setExecuteTime(String.valueOf(executeTime));
            qrtzJobLogService.save(log);
        }
    }

}
